<template>
  <!--  车间日报表-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" :rules="formRules" ref="searchForm" class="demo-form-inline"
               label-width="auto">
        <el-form-item label="工厂/车间" prop="organizationId">
          <el-tree-select v-model="searchParam.organizationId" @change="handleOrganizationChange" filterable
                          :data="workRoomList" check-strictly style="width: 220px"
                          :props="{ children: 'sonList', label: 'orgName', value: 'id' }"/>
        </el-form-item>
        <el-form-item label="设备" prop="equipmentIds" style="width: 410px">
          <el-select v-model="searchParam.equipmentIds" placeholder="请选择设备" collapse-tags collapse-tags-tooltip
                     :max-collapse-tags="2" clearable filterable multiple>
            <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentCode" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="时间区间" prop="times" style="width: 450px">
          <el-date-picker v-model="searchParam.times" type="datetimerange" start-placeholder="开始时间"
                          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="报工人">
          <el-input v-model="searchParam.userName" placeholder="请输入报工人名称" clearable style="width: 250px"/>
        </el-form-item>
        <el-form-item label="物料">
          <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable style="width: 220px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="submitForm()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 290px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="orgName" label="车间" align="center" min-width="200"/>
        <el-table-column prop="reportDate" label="日期" align="center" min-width="200"/>
        <el-table-column prop="materialNo" label="物料" align="center" min-width="250" show-overflow-tooltip/>
        <!--				<el-table-column prop="equipmentName" label="设备" align="center" min-width="250" show-overflow-tooltip />-->
        <el-table-column prop="equipmentCode" label="设备编号" align="center" min-width="250" show-overflow-tooltip/>
        <el-table-column prop="reportShift" label="班次" align="center" min-width="200">
          <template #default="scope">
            {{ reportShiftSet(scope.row.reportShift) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="班次产量" align="center" min-width="200"/>
        <el-table-column prop="qualifiedCount" label="合格数量" align="center" min-width="200"/>
        <el-table-column prop="percentOfPass" label="合格率" align="center" min-width="200"/>
        <el-table-column prop="noQualifiedCount" label="不合格产量" align="center" min-width="200"/>
        <el-table-column prop="noPercentOfPass" label="不合格率" align="center" min-width="200"/>
        <el-table-column prop="scrapCount" label="报废数量" align="center" min-width="200"/>
        <el-table-column prop="scrapPercent" label="报废率" align="center" min-width="200"/>
        <el-table-column prop="userName" label="报工人" align="center" min-width="200"/>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import {ElMessage, ElForm} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import axios from 'axios';
import moment from 'moment';

onMounted(() => {
  // getList();
  getOption();
});

const searchForm = ref<InstanceType<typeof ElForm>>();

const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/reportWorkRecord/reportWorkRecordReportDayExcel', {
    ...searchParam.value,
    ...{
      startDate: searchParam.value?.times?.[0],
      endDate: searchParam.value?.times?.[1]
    }
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '车间日报表' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};


const pageTotal = ref(null); // 页面总数
const searchParam = ref({
  times: [
    dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
});

const paginatedData = ref([]);
const workRoomList = ref([]); // 车间
const equipmentData = ref([]);

const formRules = ref({
  organizationId: [{required: true, message: '请选择工厂/车间', trigger: 'change'}],
  equipmentIds: [{required: true, message: '请选择设备', trigger: 'change'}],
  times: [{required: true, message: '请选择设备', trigger: 'change'}]
});

const handleOrganizationChange = (value) => {
  searchParam.value.equipmentIds = [];
  axiosInstance.post('/api/basedataEquipment/getAll', {organizationId: value}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    equipmentData.value = res.data;
    searchParam.value.equipmentIds = res.data.map(item => item.id);
  });
};

const getOption = () => {
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};

const reportShiftSet = (reportShift) => {
  switch (reportShift) {
    case 0:
      return '早班';
    case 1:
      return '中班';
    case 2:
      return '晚班';
    default:
      return '';
  }
}

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/reportWorkRecord/reportWorkRecordReportDay', {
    ...searchParam.value,
    startDate: searchParam.value?.times?.[0],
    endDate: searchParam.value?.times?.[1],
    times: undefined,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 提交表单
const submitForm = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      getList();
    }
  });
};

// 重置搜索条件
const resetSearch = () => {
  pageSearch.value.current = 1;
  searchForm.value.clearValidate();
  searchParam.value = {
    times: [
      dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  };
  // submitForm()
};
</script>
<style scoped></style>